﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
using DailyPhoto.Entities;
using DailyPhoto.Common;

namespace DailyPhoto
{
    public static class Util
    {
        public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio = Math.Min(ratioX, ratioY);

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
            return newImage;
        }

        public static void SendMail(string email,string attachment = null, string body = null,bool admin = false)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

            message.To.Add(email);

            if (attachment != null && File.Exists(attachment))
            {
                message.Attachments.Add(new System.Net.Mail.Attachment(attachment));
            }

            message.Subject = string.Format("Daily Photo {0}", DateTime.Now.ToString("dd/MM/yy HH:mm"));

            message.From = new System.Net.Mail.MailAddress((string)Application.Config.sender.email, (string)Application.Config.sender.from);

            message.IsBodyHtml = true;

            message.Body = "";

            
            if (body != null)
            {
                message.Body +=
                "<div id=\"content\" style=\"border:4px solid red;width:90%;font-size: 18pt;font-family: Arial,Verdana;padding:8px;text-align:left;margin: 10px 10px 20px 20px;\">";

                message.Body += body;

                message.Body += "</div>";
            }

            
            if (admin)
            {
                var link = string.Format("http://omkoren.ath.cx:3032/kupa/dailyphoto/generate?token={0}",
                                          (string)Application.Config.webToken);


                message.Body += "<a href=\"" + link + "\">";
                message.Body += "Send me another daily photo";
                message.Body += "</a>";    
            }

            var smtp = new System.Net.Mail.SmtpClient
            {
                Host = (string)Application.Config.sender.smtp.host,
                Port = (int)Application.Config.sender.smtp.port,
                EnableSsl = true,
                DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new System.Net.NetworkCredential((string)Application.Config.sender.username,
                                                                (string)Application.Config.sender.password)
            };

            using (message)
            {
                smtp.Send(message);
            }
        }

        public static T[] ShuffleArray<T>(T[] arr)
        {
            List<KeyValuePair<int, T>> list = new List<KeyValuePair<int, T>>();

            Random _random = new Random(Environment.TickCount);
            // Add all strings from array
            // Add new random int each time
            foreach (T s in arr)
            {
                list.Add(new KeyValuePair<int, T>(_random.Next(), s));
            }
            // Sort the list by the random number
            var sorted = from item in list
                         orderby item.Key
                         select item;

            // Allocate new string array
            T[] result = new T[arr.Length];
            // Copy values to array
            int index = 0;
            foreach (var pair in sorted)
            {
                result[index] = pair.Value;
                index++;
            }
            // Return copied array
            return result;
        }

        public static IEnumerable<FileInfo> ListAllFiles(DirectoryInfo dir)
        {
            var lst = new List<FileInfo>();

            lst.AddRange(dir.GetFiles());

            foreach (var subdir in dir.GetDirectories())
            {
                lst.AddRange(ListAllFiles(subdir));
            }

            return lst;
        }

        public static RotateFlipType OrientationToFlipType(string orientation)
        {
            switch (int.Parse(orientation))
            {
                case 1:
                    return RotateFlipType.RotateNoneFlipNone;
                    break;
                case 2:
                    return RotateFlipType.RotateNoneFlipX;
                    break;
                case 3:
                    return RotateFlipType.Rotate180FlipNone;
                    break;
                case 4:
                    return RotateFlipType.Rotate180FlipX;
                    break;
                case 5:
                    return RotateFlipType.Rotate90FlipX;
                    break;
                case 6:
                    return RotateFlipType.Rotate90FlipNone;
                    break;
                case 7:
                    return RotateFlipType.Rotate270FlipX;
                    break;
                case 8:
                    return RotateFlipType.Rotate270FlipNone;
                    break;
                default:
                    return RotateFlipType.RotateNoneFlipNone;
            }
        }

        public static void GenerateDailyPhoto()
        {
            try
            {
                var all = new List<Photo>();

                foreach (var repo in Repositories.All)
                {
                    all.AddRange(repo.Fetch());
                }

                var arr = Util.ShuffleArray(all.ToArray());

                var rnd = new Random(Environment.TickCount);
                var photo = arr[rnd.Next(arr.Length - 1)];

                var filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP"),
                                            string.Format("dailyphoto-{0}.jpg", DateTime.Now.ToString("dd-MM-yy")));

                photo.SaveFile(filename);

                
                foreach (var email in Application.Config.mails)
                {
                    Util.SendMail(email.ToString(),filename);
                }

                foreach (var email in Application.Config.powerUsers)
                {
                    Util.SendMail(email.ToString(), filename,null,true);
                }
                /*
                */
                foreach (var email in Application.Config.adminUsers)
                {
                    Util.SendMail(email.ToString(), filename, null, true);
                }
                
                new BlackList().Insert(new BlackEntry() { 
                    PhotoId = photo.PhotoId, 
                    RepositoryName = photo.RepositoryName,
                    Date = DateTime.Now
                });

                File.Delete(filename);

            }
            catch (Exception ex)
            {
                try
                {
                    string body = "Error while generating the daily photo:<br /><br />";
                    body += ex.Message;
                    body += "<br /><br />";
                    body += ex.StackTrace;

                    foreach (var email in Application.Config.adminUsers)
                    {
                        Util.SendMail(email.ToString(), body: body, admin: true);
                    }
                }
                catch (Exception) { } 
                Logger.Write(ex);
            }
        }

    }

}
